#include "stdafx.h"
#include "UniformBufferObject.h"

UniformBufferObject::UniformBufferObject(GLenum bufUsage)
{
	m_uboName = 0;
	m_bufUsage = bufUsage;
}

UniformBufferObject::~UniformBufferObject()
{
	if (m_uboName) glDeleteBuffers(1, &m_uboName);
}

void UniformBufferObject::Init(GLuint blockSize, void *blockBuffer, GLuint bindPoint)
{
	_ASSERT(!m_uboName);
	m_bindPoint = bindPoint;
	glGenBuffers(1, &m_uboName);
	glBindBuffer(GL_UNIFORM_BUFFER, m_uboName);
	glBufferData(GL_UNIFORM_BUFFER, blockSize, blockBuffer, m_bufUsage);
	glBindBufferBase(GL_UNIFORM_BUFFER, bindPoint, m_uboName);
	glBindBuffer(GL_UNIFORM_BUFFER, 0);
}

void UniformBufferObject::Init(char *uniformBlockName, GLuint program, GLuint bindPoint)
{
	int loc1 = glGetUniformBlockIndex(program, uniformBlockName);
	int sz1;
	glGetActiveUniformBlockiv(program, loc1, GL_UNIFORM_BLOCK_DATA_SIZE, &sz1);
	Init(sz1, 0, bindPoint);
	QueryOffset(program);
}

//void UniformBufferObject::SetBindPoint(GLuint bindPoint)
//{
//	glBindBufferBase(GL_UNIFORM_BUFFER, bindPoint, m_uboName);
//}

GLuint UniformBufferObject::GetBindPoint()
{
	return m_bindPoint;
}

void UniformBufferObject::SetBufferData(int offset, int size, void *data, bool bind)
{
	if (bind) glBindBuffer(GL_UNIFORM_BUFFER, m_uboName);
	glBufferSubData(GL_UNIFORM_BUFFER, offset, size, data);
}

GLuint UniformBufferObject::GetUboName()
{
	return m_uboName;
}

void UniformBufferObject::Bind()
{
	glBindBuffer(GL_UNIFORM_BUFFER, m_uboName);
}

void UniformBufferObject::UnBind()
{
	glBindBuffer(GL_UNIFORM_BUFFER, 0);
}